﻿using Xejen.Communication.Http.Configuration;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;

namespace Xejen.Communication.Http.Abstract
{
    /// <summary>
    /// 表示表单的<see langword="ContentType"/>内容策略
    /// </summary>
    internal class FormUrlEncodedContentStrategy : ContentStrategyBase, IHttpContentStrategy
    {
        /// <inheritdoc cref="FormUrlEncodedContentStrategy"/>
        /// <param name="config"><inheritdoc/></param>
        public FormUrlEncodedContentStrategy(HttpConfig config) : base(config) { }

        /// <inheritdoc/>
        public override HttpContent CreateHttpContent(object data)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            //string contentType = HttpConfig.ContentType;
            string contentType = "application/x-www-form-urlencoded";

            if ((data is Dictionary<string, string> formData))
            {
                var content = new FormUrlEncodedContent(formData);
                content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
                return content;
            }

            if (data is MultipartFormDataContent formDataContent)
            {
                formDataContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
                return formDataContent;
            }

            throw new NotImplementedException($"数据非法，由于您的内容格式为：{contentType}，所以，您传入的参数必须是这两种类型：{typeof(Dictionary<string, string>)} 或者 {typeof(MultipartFormDataContent)}");
        }
    }
}